package com.huaxin.message.sms.tencent;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class SmsService {
    @Value("${tencent.cloud.secretId}")
    private String secretId;

    @Value("${tencent.cloud.secretKey}")
    private String secretKey;

    @Value("${tencent.cloud.appId}")
    private String appId;
    @Value("${tencent.cloud.sign}")
    private String sign;

    /**
     * 发送短信
     *
     * @param phoneNumber      手机号
     * @param templateId       模板ID
     * @param templateParamSet 模板参数
     */
    public Boolean sendSms(String phoneNumber, String templateId, String[] templateParamSet) throws TencentCloudSDKException {
        Credential cred = new Credential(secretId, secretKey);
        SmsClient client = new SmsClient(cred, "");
        SendSmsRequest req = new SendSmsRequest();
        req.setSmsSdkAppid(appId);
        req.setSign(sign);
        req.setPhoneNumberSet(new String[]{phoneNumber});
        req.setTemplateID(templateId);
        req.setTemplateParamSet(templateParamSet);
        SendSmsResponse resp = client.SendSms(req);
        System.out.println(SendSmsResponse.toJsonString(resp));
        return resp.getSendStatusSet()[0].getCode().equals("Ok");
    }

    public String formatPhoneNumber(String phoneNumber) {
        // 检查是否已包含国际前缀"+86"
        if (!phoneNumber.startsWith("+86")) {
            // 如果没有，则添加前缀
            return "+86" + phoneNumber;
        }
        // 如果已经有前缀，则直接返回原号码
        return phoneNumber;
    }
}
